package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.dao.JazCoursesOrderDao;
import com.jinzhi.jzweb.dao.JazUserCommentDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.JazCoursesTeacherVo;
import com.jinzhi.jzweb.domain.vo.JazCoursesVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.wxpay.enums.OrderStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazCoursesDao;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 课程表
 * </pre>
 * <small> 2024-05-13 16:52:34 | Long</small>
 */
@Service
public class JazCoursesServiceImpl extends CoreServiceImpl<JazCoursesDao, JazCoursesDO> implements JazCoursesService {

    private final JazCoursesTeacherService jazCoursesTeacherService;

    private final JazCoursesChapterService jazCoursesChapterService;

    private final JazCoursesOrderDao jazCoursesOrderDao;

    private final DictService dictService;

    public JazCoursesServiceImpl(JazCoursesTeacherService jazCoursesTeacherService,JazCoursesChapterService jazCoursesChapterService,JazCoursesOrderDao jazCoursesOrderDao,DictService dictService){
        this.jazCoursesTeacherService = jazCoursesTeacherService;
        this.jazCoursesChapterService = jazCoursesChapterService;
        this.jazCoursesOrderDao = jazCoursesOrderDao;
        this.dictService = dictService;
    }

    public UserDO getUser() {
        return ShiroUtils.getSysUser();
    }

    public Long getUserId() {
        return getUser().getId();
    }
    /**
     * 阿姨端课程首页列表接口
     * @param jazCoursesDTO 课程表单
     * @return
     */
    @Override
    public Result<Page<JazCoursesDO>> auntCoursesList(JazCoursesDO jazCoursesDTO) {
        //分页
        Page<JazCoursesDO> jazCoursesDOPage = new Page<>(jazCoursesDTO.getCurrent(), jazCoursesDTO.getSize());
        Page<JazCoursesDO> pageList = this.selectPage(jazCoursesDOPage, new EntityWrapper<JazCoursesDO>().eq("state",0).orderBy("creater_date",false));
        List<JazCoursesDO> records = pageList.getRecords();
        if(records!=null && records.size()>0){
            records.forEach(record -> {
                //查询主讲老师
                List<JazCoursesTeacherDO> jazCoursesTeacherDOS = jazCoursesTeacherService.selectList(new EntityWrapper<JazCoursesTeacherDO>().eq("courses_id", record.getId()).orderBy("sort", true));
                if(jazCoursesTeacherDOS!=null && jazCoursesTeacherDOS.size()>0){
                    // 使用逗号拼接讲师名称
                    String teacherName = jazCoursesTeacherDOS.stream().map(JazCoursesTeacherDO::getTeacherName).collect(Collectors.joining(","));
                    record.setTeacherName(teacherName);
                }
            });
            pageList.setRecords(records);
        }

        return Result.ok(pageList);
    }

    /**
     * 阿姨端查询课程详情 （包括课程介绍、销量、价格等）
     * @param coursesId 课程id
     * @return
     */
    @Override
    public Result<JazCoursesDO> auntCoursesDetail(Long coursesId) {
        //查询课程信息
        Long userId = JWTUtil.getUser().getId();
//        Long userId = 1788836462968561666L;
        JazCoursesDO jazCoursesDO = this.selectById(coursesId);
        //查询销量
        int i = jazCoursesOrderDao.selectCount(new EntityWrapper<JazCoursesOrderDO>().eq("courses_id", coursesId).eq("status",OrderStatus.SUCCESS.getType()));
        jazCoursesDO.setSales(i+getCourseSales());
        //查询用户是否购买 || 价格为0的也算购买
        if(jazCoursesDO.getPrice().compareTo(BigDecimal.ZERO)==0){
            jazCoursesDO.setHasBuy(true);
            return Result.ok(jazCoursesDO);
        }
        JazCoursesOrderDO jazCoursesOrderDTO = new JazCoursesOrderDO();
        jazCoursesOrderDTO.setCoursesId(coursesId);
        jazCoursesOrderDTO.setUserId(userId);
        jazCoursesOrderDTO.setStatus(OrderStatus.SUCCESS.getType());
        JazCoursesOrderDO jazCoursesOrderDO = jazCoursesOrderDao.selectOne(jazCoursesOrderDTO);
        if(jazCoursesOrderDO!=null){
            jazCoursesDO.setHasBuy(true);
        }
        return Result.ok(jazCoursesDO);
    }

    /**
     * 阿姨端获取课程父章节 并且获取判断是否存在子章节
     * @param id
     * @return
     */
    @Override
    public Result<List<JazCoursesChapterDO>> auntParentChapter(Long id) {
        List<JazCoursesChapterDO> chapterList = jazCoursesChapterService.selectList(new EntityWrapper<JazCoursesChapterDO>().eq("parent_id", id).orderBy("sort",true));
        if(chapterList!=null && !chapterList.isEmpty()){
            //判断是否有子章节
            chapterList.forEach(chapter -> {
                List<JazCoursesChapterDO> childrenList = jazCoursesChapterService.selectList(new EntityWrapper<JazCoursesChapterDO>().eq("parent_id", chapter.getId()));
                if(childrenList!=null && !childrenList.isEmpty()){
                    chapter.setHasChildren(true);
                }
            });
        }
        return Result.ok(chapterList);
    }

    /**
     * 月嫂课程浏览量新增
     * @param courseId 课程id
     * @return
     */
    @Override
    public Result<?> addBrowseNum(Long courseId) {
        JazCoursesDO jazCoursesDO = this.selectById(courseId);
        //浏览量+1
        jazCoursesDO.setBrowseNum(jazCoursesDO.getBrowseNum()+1);
        boolean b = this.updateById(jazCoursesDO);

        return b? Result.ok() : Result.fail();
    }

    @Override
    public Result<Page<JazCoursesDO>> selCourseList(String name, String teacherName, int current, int size) {
        Page<JazCoursesDO> page = new Page<>(current, size);
        List<JazCoursesDO> voList=new ArrayList<>();
        Wrapper<JazCoursesDO> wrapper=new EntityWrapper<>();
        if (StringUtils.isNotBlank(name)){
            wrapper.like("name",name);
        }
        if (StringUtils.isNotBlank(teacherName)){
            List<JazCoursesTeacherDO> teacherName1 = jazCoursesTeacherService.selectList(new EntityWrapper<JazCoursesTeacherDO>().like("teacher_name", "%"+teacherName+"%"));
            if (!teacherName1.isEmpty()){
                List<Long> collect = teacherName1.stream().map(JazCoursesTeacherDO::getCoursesId).collect(Collectors.toList());
                wrapper.in("id",collect);
            }
        }
        wrapper.orderBy("sort");
        Page<JazCoursesDO> jazCoursesDOPage = this.selectPage(page, wrapper);
        for (JazCoursesDO jazCoursesDO:jazCoursesDOPage.getRecords()){
            JazCoursesDO vo=new JazCoursesDO();
            BeanUtils.copyProperties(jazCoursesDO,vo);
            List<JazCoursesTeacherDO> jazCoursesTeacherDOS = jazCoursesTeacherService.selectList(new EntityWrapper<JazCoursesTeacherDO>().eq("courses_id", jazCoursesDO.getId()).orderBy("sort"));
            List<String> collect = jazCoursesTeacherDOS.stream().map(JazCoursesTeacherDO::getTeacherName).collect(Collectors.toList());
            vo.setTeacherNames(collect.toString());
            voList.add(vo);
        }
        jazCoursesDOPage.setRecords(voList);

        return Result.ok(jazCoursesDOPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCourse(JazCoursesVo jazCoursesVo) {
        JazCoursesDO jazCoursesDO=new JazCoursesDO();
        BeanUtils.copyProperties(jazCoursesVo,jazCoursesDO);
        jazCoursesDO.setState(0);
        jazCoursesDO.setCreaterId(this.getUserId());
        this.insert(jazCoursesDO);

        List<JazCoursesTeacherVo> voList = jazCoursesVo.getVoList();
        for (JazCoursesTeacherVo vo:voList){
            JazCoursesTeacherDO jazCoursesTeacherDO=new JazCoursesTeacherDO();
            jazCoursesTeacherDO.setCoursesId(jazCoursesDO.getId());
            jazCoursesTeacherDO.setTeacherName(vo.getTeacherName());
            jazCoursesTeacherDO.setSort(vo.getSort());
            jazCoursesTeacherDO.setTeacherIntroduce(vo.getTeacherIntroduce());
            jazCoursesTeacherService.insert(jazCoursesTeacherDO);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCourse(JazCoursesVo jazCoursesVo) {
        JazCoursesDO jazCoursesDO = this.selectById(jazCoursesVo.getId());
        BeanUtils.copyProperties(jazCoursesVo,jazCoursesDO);
        jazCoursesDO.setUpdaterId(this.getUserId());

//        jazCoursesDO.setUpdaterId(1504759468294201346L);
        jazCoursesDO.setUpdateDate(new Date());
        this.updateById(jazCoursesDO);
        List<JazCoursesTeacherVo> voList = jazCoursesVo.getVoList();
        for (JazCoursesTeacherVo vo:voList){
            JazCoursesTeacherDO jazCoursesTeacherDO = jazCoursesTeacherService.selectById(vo.getTeacherId());
            jazCoursesTeacherDO.setCoursesId(jazCoursesDO.getId());
            jazCoursesTeacherDO.setTeacherName(vo.getTeacherName());
            jazCoursesTeacherDO.setSort(vo.getSort());
            jazCoursesTeacherDO.setTeacherIntroduce(vo.getTeacherIntroduce());
            if (vo.getIsDelete() != null && vo.getTeacherId() != null) {
                // 先判断是否需要删除
                jazCoursesTeacherService.deleteById(vo.getTeacherId());
            } else if (vo.getTeacherId() != null) {
                // 然后判断ID是否存在，存在则更新
                jazCoursesTeacherDO.setId(vo.getTeacherId());
                jazCoursesTeacherService.updateById(jazCoursesTeacherDO);
            } else {
                // ID不存在，说明是新记录，执行插入
                jazCoursesTeacherService.insert(jazCoursesTeacherDO);
            }
        }
    }

    /**
     * 我的学习列表
     * @return
     */
    @Override
    public Result<?> learningList() {
        Long userId = JWTUtil.getUser().getId();
        //我的学习分为两部分（1.购买的课程 2.免费的课程）
        List<JazCoursesDO> coursesList = new ArrayList<>();
        //1.查询用户购买的课程
        List<JazCoursesOrderDO> jazCoursesOrderDOS = jazCoursesOrderDao.selectList(new EntityWrapper<JazCoursesOrderDO>().eq("user_id", userId).eq("status", OrderStatus.SUCCESS.getType()));
        if(null!=jazCoursesOrderDOS && !jazCoursesOrderDOS.isEmpty()){
            jazCoursesOrderDOS.forEach(jazCoursesOrderDO -> {
                JazCoursesDO jazCoursesDO = this.selectById(jazCoursesOrderDO.getCoursesId());
                coursesList.add(jazCoursesDO);
            });
        }

        //2.查询免费的课程
        List<JazCoursesDO> jazCoursesDOS = this.selectList(new EntityWrapper<JazCoursesDO>().eq("price", 0).eq("state", 0));
        if(null!=jazCoursesDOS){
            coursesList.addAll(jazCoursesDOS);
        }

        //3.查询课程老师
        if(coursesList!=null && !coursesList.isEmpty()){
            coursesList.forEach(jazCoursesDO->{
                //查询主讲老师
                List<JazCoursesTeacherDO> jazCoursesTeacherDOS = jazCoursesTeacherService.selectList(new EntityWrapper<JazCoursesTeacherDO>().eq("courses_id", jazCoursesDO.getId()).orderBy("sort", true));
                if(jazCoursesTeacherDOS!=null && jazCoursesTeacherDOS.size()>0){
                    // 使用逗号拼接讲师名称
                    String teacherName = jazCoursesTeacherDOS.stream().map(JazCoursesTeacherDO::getTeacherName).collect(Collectors.joining(","));
                    jazCoursesDO.setTeacherName(teacherName);
                }
            });
        }

        return Result.ok(coursesList);
    }


    public Integer getCourseSales(){
        Integer courseSales = 300;//客服电话
        Map map = new HashMap();
        map.put("Type","course_sales");
        List<DictDO> dictDOS = dictService.selectListBy(map);
        if(dictDOS!=null && !dictDOS.isEmpty()){
            courseSales = Integer.valueOf(dictDOS.get(0).getValue());
        }
        return courseSales;
    }


}
